package com.gopay.cashier.dao.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.gopay.cashier.dao.CommonDAO;
import com.gopay.common.base.dao.impl.BaseDAOImpl;
import com.gopay.common.util.ClassesUtil;

@SuppressWarnings("unchecked")
public class CommonDAOImpl<T extends Serializable, Pk extends Serializable> extends BaseDAOImpl<T, Pk> implements
        CommonDAO<T, Pk> {

    @Autowired
    private HibernateTemplate hibernateTemplate;
    private Class<T> persistentClass;

    public CommonDAOImpl() {
        this.persistentClass = ClassesUtil.getSuperClassGenericType(getClass());
    }

    public CommonDAOImpl(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    @Override
    public String getEntityName() {
        return persistentClass.getSimpleName();
    }

    @Override
    public T get(Pk id) {
        return this.getHibernateTemplate().get(this.persistentClass, id);
    }

    public void delete(T entity) {
        getHibernateTemplate().delete(entity);
    }

    public void deleteAll(Collection<T> collection) {
        getHibernateTemplate().deleteAll(collection);
    }

    public List<T> findByExample(T entity) {
        return getHibernateTemplate().findByExample(entity);
    }

    public List<T> findAll(Class<T> entityClass) {
        return getHibernateTemplate().loadAll(entityClass);
    }

    public void update(T entity) {
        getHibernateTemplate().update(entity);
    }

    public T find(Class<T> entity, Pk id) {
        return (T) getHibernateTemplate().get(entity, id);
    }

    public List<T> findByCriteria(DetachedCriteria criteria) {
        return getHibernateTemplate().findByCriteria(criteria);
    }

    public List<T> findBySql(final String sql) {
        return findBySql(sql, null);
    }

    @Override
    public T save(T entity) {
        return (T) hibernateTemplate.save(entity);
    }
}
